import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.bson.types.ObjectId;

import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;

import devboard.dbutil.MongoUtil;

@WebServlet("/AJAXHandler")
public class AJAXBoardHandler extends HttpServlet {
	
	private enum Reason {
		
		SAVE_DELIVER_INFO{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id",new ObjectId(id)));
				if(task!=null){
					task.put("revision", request.getParameter("revision"));
					task.put("branch", request.getParameter("branch"));
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
					return "";
				}else{
					return "error";
				}
			}
		},
		GET_DELIVER_INFO{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id",new ObjectId(id)));
				if(task!=null){
					StringBuilder response=new StringBuilder("");
					response.append("<table>");
					response.append("<tr><td>revision:</td><td><input id=\"deliverInfoRevision\" size=\"3\" type=\"text\" value=\""+
								task.get("revision")+"\"></td></tr>");
					response.append("<tr><td>branch:</td><td><input id=\"deliverInfoBranch\" size=\"3\" type=\"text\" value=\""+
							task.get("branch")+"\"></td></tr>");
					response.append("</table>");
					response.append("<button onclick=\"closePopup(deliverInfo)\">close</button>");
					response.append("<button onclick=\"saveDeliverInfo()\">save</button>");
					return response.toString();
				}else{
					return "";
				}
			}
		},
		IMPORT_FROM_CSV{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				
				File file=new File("/home/paskal/projects.htm");
				InputStreamReader inf = new InputStreamReader(new FileInputStream(file));
				StringBuilder fileText=new StringBuilder();
				int ch;
				while((ch=inf.read())>=0){
					fileText.append((char)ch);
				}
				inf.close();
				
				
				InputStreamReader in = new InputStreamReader(request.getInputStream());
				StringBuilder s=new StringBuilder();
				int c;
				while((c=in.read())>=0){
					s.append((char)c);
				}
				in.close();
				//clean text
				s.delete(0, s.indexOf("\n")+1);
				s.delete(0, s.indexOf("\n")+1);
				s.delete(0, s.indexOf("\n")+1);
				s.delete(s.lastIndexOf("\n"), s.length());
				s.delete(s.lastIndexOf("\n"), s.length());
				//convert to array[][]
				String[] temp=s.toString().trim().split("\n");
				String[][] str=new String[temp.length][];
				for(int i=0;i<temp.length;i++){
					str[i]=temp[i].split(";");
				}
				//convert array[][] to list
				ArrayList<HashMap<String, String>> taskList=new ArrayList<HashMap<String,String>>();
				for(int i=1;i<str.length;i++){
					HashMap<String, String> map=new HashMap<String, String>();
					for(int j=0;j<str[i].length;j++){
						map.put(str[0][j], str[i][j]);
					}
					taskList.add(map);
				}
				//add to database
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				BasicDBObject[] docs=new BasicDBObject[taskList.size()];
				for(int i=0;i<docs.length;i++){
					docs[i]=new BasicDBObject();
					docs[i].put("subId", taskList.get(i).get("Sub ID"));
					docs[i].put("project", taskList.get(i).get("Team")); 
					docs[i].put("serviceType", taskList.get(i).get("Service Type"));
					docs[i].put("name", taskList.get(i).get("Project Name"));
					
					String temp1=fileText.substring(fileText.indexOf("/projects/projects/show/"+taskList.get(i).get("Project ID")));
					temp1=temp1.substring(temp1.indexOf("http://issue-tracker.gdev.com/"));
					docs[i].put("link", temp1.substring(0,temp1.indexOf("\"")));

					
					
					docs[i].put("estimate", "5");
					docs[i].put("checked", "");
					docs[i].put("userId", "nobody");
					docs[i].put("reproduced", "no");
					docs[i].put("inProgress", "no");
					docs[i].put("delivered", "no");
					docs[i].put("successfully", "no");
					docs[i].put("timeCreation", System.currentTimeMillis());
					docs[i].put("projectId", taskList.get(i).get("Project ID"));
					docs[i].put("release", taskList.get(i).get("Release ID"));
				}
				tasks.insert(docs);
				return "";
			}
		},
		UNPAYD_JOB{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id",new ObjectId(id)));
				if((((String)request.getSession().getAttribute("role")).equals("manager"))&&
						(task!=null)){
					task.put("paid", request.getParameter("paid"));
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
					MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
							(String)request.getSession().getAttribute("lastName")
							+"</b> has unpaid job.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
					return "success";
				}else{
					return "";
				}
			}
		},
		PAY_FOR_JOB{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id", new ObjectId(id)));
				if((((String)request.getSession().getAttribute("role")).equals("manager"))&&
						(task!=null)){
					task.put("paid", request.getParameter("paid"));
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
					MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
							(String)request.getSession().getAttribute("lastName")
							+"</b> has paid for job.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
					return "<img src=\"css/coins.png\" width=\"30\">";
				}else{
					return "";
				}
			}
		},
		UPDATE_TASK{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id", new ObjectId(id)));
				if(task!=null){
					task.put("name", request.getParameter("name"));
					task.put("link", request.getParameter("link"));
					task.put("userId", request.getParameter("account_id"));
					task.put("projectId", request.getParameter("project_id"));
					task.put("release", request.getParameter("release"));
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
					MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
							(String)request.getSession().getAttribute("lastName")
							+"</b> has updated task.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
					return "success";
				}else{
					return "error";
				}
			}
		},
		UPDATE_TASK_STATUS{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id", new ObjectId(id)));
				if(task!=null){
					if(((String)request.getSession().getAttribute("_id")).equals(task.get("userId"))){
						if(task.get(request.getParameter("name")).equals("issue")){
							return (String)task.get("issue");
						}else{
							String status=task.get(request.getParameter("name")).equals("no")?"yes":"no";
							task.put(request.getParameter("name"), status);
							tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
							MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
									(String)request.getSession().getAttribute("lastName")
									+"</b> has updated task's status.","devboard", (String)request.getSession().getAttribute("_id"), "iframe_frame_Board");
							return status;
						}
					}else{
						if(task.get(request.getParameter("name")).equals("issue")){
							return (String)task.get("issue");
						}
						else return "no_rights";	
					}
				}else{
					return "internal server error";
				}
			}
		},
		DELETE_TASK{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findAndRemove(new BasicDBObject("_id", new ObjectId(request.getParameter("id"))));
				if(task==null){
					return "error";
				}
				MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
						(String)request.getSession().getAttribute("lastName")
						+"</b> has deleted the task.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
				return "deleted";
			}
		},
		CREATE_ISSUE{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id", new ObjectId(id)));
				String issue=request.getParameter("issueContent");
				if((issue!=null)&&(task!=null)){
					if(task.get("reproduced").equals("no")){
						task.put("reproduced", "issue");
					}else if(task.get("inProgress").equals("no")){
						task.put("inProgress", "issue");
					}else if(task.get("delivered").equals("no")){
						task.put("delivered", "issue");
					}else if(task.get("successfully").equals("no")){
						task.put("successfully", "issue");
					}
					task.put("issue",issue);
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
				}
				MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
						(String)request.getSession().getAttribute("lastName")
						+"</b> has created issues.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
				return "";
			}
		},
		RESOLVE_ISSUE{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				String id=request.getParameter("id");
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				DBObject task=tasks.findOne(new BasicDBObject("_id", new ObjectId(id)));
				if(task!=null){
					String status="no";
					task.put(request.getParameter("name"), status);
					tasks.update(new BasicDBObject("_id", new ObjectId(id)),task);
					MongoUtil.sendMessage("The user <b>"+(String)request.getSession().getAttribute("firstName")+
							(String)request.getSession().getAttribute("lastName")
							+"</b> has resolved to issue.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
					return status;
				}else{
					return "error";
				}
			}
		},
		ADD_TASK{
			@Override
			public String processRequest(HttpServletRequest request) throws IOException{
				DBCollection tasks=MongoUtil.getCollection("Tasks");
				BasicDBObject task=new BasicDBObject();
				task.put("project", request.getParameter("team"));
				task.put("name", request.getParameter("name"));
				task.put("link", request.getParameter("link"));
				task.put("userId", "nobody");
				task.put("reproduced", "no");
				task.put("inProgress", "no");
				task.put("delivered", "no");
				task.put("successfully", "no");
				task.put("timeCreation", System.currentTimeMillis());
				task.put("projectId", request.getParameter("projectId"));
				tasks.insert(task);
				MongoUtil.sendMessage("User <b>"+(String)request.getSession().getAttribute("firstName")+
						(String)request.getSession().getAttribute("lastName")
						+"</b> added a new task.","devboard", (String)request.getSession().getAttribute("_id"),"iframe_frame_Board");
				return "";
			}
		};
		
		public abstract String processRequest(HttpServletRequest request) throws IOException;
		
	}
	
	private static final long serialVersionUID = 1L;

    public AJAXBoardHandler() {
        super();
    }
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Reason reason=Reason.valueOf(request.getParameter("reason"));
		response.getWriter().print(reason.processRequest(request));
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		Reason reason=Reason.valueOf(request.getParameter("reason"));
		response.getWriter().print(reason.processRequest(request));
	}

}
